package cn.izeno.wx

import cn.izeno.wx.models.TokenApp
import cn.izeno.wx.service.WeappService
import okhttp3.OkHttpClient
import retrofit2.Retrofit
import retrofit2.adapter.rxjava3.RxJava3CallAdapterFactory
import retrofit2.converter.fastjson.FastJsonConverterFactory
import retrofit2.converter.simplexml.SimpleXmlConverterFactory

object Weapp {
  val weapp: WeappService

  init {
    val retrofit = Retrofit.Builder().baseUrl("https://api.weixin.qq.com/")
        .client(OkHttpClient())
        .addCallAdapterFactory(RxJava3CallAdapterFactory.createSynchronous())
        .addConverterFactory(FastJsonConverterFactory.create())
        .addConverterFactory(SimpleXmlConverterFactory.create())
        .build()
    weapp = retrofit.create(WeappService::class.java)
  }


  fun appAccessToken(appId: String, appSecret: String, refresh: Boolean = false): String {
    val key = "app_access_token:$appId"
    if (refresh) cn.izeno.wx.Cache[key] = null
    val token: TokenApp? = cn.izeno.wx.Cache["app_access_token:$appId"] as? TokenApp
    if (token != null && token.expiredAt > System.currentTimeMillis()) {
      return token.accessToken
    }

    var accessToken: String? = null
    weapp.appAccessToken(appId, appSecret)
        .doOnNext {
          it.expiredAt = it.expiredIn * 1000 + System.currentTimeMillis()
          cn.izeno.wx.Cache["app_access_token:$appId"] = it
        }
        .subscribe {
          accessToken = it.accessToken
        }

    return accessToken ?: ""
  }
}